from django.shortcuts import render, HttpResponse
import requests
import json
from django.views.decorators.csrf import csrf_exempt
import logging

# 实例化log的对象
visit_logger = logging.getLogger("visit")


@csrf_exempt
def seo_api(request):
    if request.method == 'POST':
        key = request.POST.get('key')
        number = request.POST.get('number')
        if key == None or number== None:
            return HttpResponse(json.dumps('key或者number为空'))
        ret = key_recommend(key, number)

        if ret:
            return HttpResponse(json.dumps(ret))

        return HttpResponse(json.dumps('当前查询出现问题,请稍后再试'))

    else:
        return HttpResponse('非法请求')


def key_price(num):
    '''
    得到单个关键词的报价
    :return:
    '''
    try:
        lis = []
        for i in range(len(num)):
            url = 'http://admin.vqseo.com/KeyWordSpread/GetReferKeyWordPriceList'
            data = {"key": num[i], "index1": "0", "index2": "0"}
            response = requests.request(method='post', url=url, data=data)

            ret = response.json()
            ret = ret['list']

            key = ret[0]['name']
            baidu_pc1 = round(ret[0]['listprice'][0]['oldprice'] * 0.95, 2)
            baidu_pc2 = round(ret[0]['listprice'][0]['secondprice'] * 0.95)

            baidu_sj1 = round(ret[0]['listprice'][3]['firstprice'] * 0.95)
            baidu_sj2 = round(ret[0]['listprice'][3]['secondprice'] * 0.95)

            sougo_sj1 = round(ret[0]['listprice'][5]['firstprice'] * 0.95)
            sougo_sj2 = round(ret[0]['listprice'][5]['secondprice'] * 0.95)

            sougopc_360_shenma_one = round(ret[0]['listprice'][1]['firstprice'] * 0.95)
            sougopc_360_shenma_two = round(ret[0]['listprice'][1]['secondprice'] * 0.95)

            lis.append({
                'key': key,
                'baidu_pc1': baidu_pc1,
                'baidu_pc2': baidu_pc2,
                'baidu_sj1': baidu_sj1,
                'baidu_sj2': baidu_sj2,
                'sougo_sj1': sougo_sj1,
                'sougo_sj2': sougo_sj2,
                'sougopc_360_shenma_one': sougopc_360_shenma_one,
                'sougopc_360_shenma_two': sougopc_360_shenma_two,

            })
        return lis

    except Exception as e:
        visit_logger.error(e)
        return None


def key_recommend(key, number):
    """
    关键词的推荐
    :return:
    """
    try:
        url = 'http://admin.vqseo.com/KeyWordSearch/GetSpreadIndexSearchList'
        data = {"keyword": str(key), 'about': int(number)}
        lis = []
        response = requests.request(method='post', url=url, data=data)
        for i in range(data['about']):
            lis.append(response.json()[i]['name'])
        ret = key_price(lis)
        return ret

    except Exception as e:
        visit_logger.error(e)
        return None
